package com.aat.dxfy.dxyStart;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class DxyStartMakeCodeV2 {
	private static String baseDir;// xlsm所在基本目录
	private static String packagePath = "com/cctv/ejinr";// com.公司名.项目名
	private static String moduleName;// 模块名
	private static String xlsmName = "model.xlsm";

	private static String packageName = "com.cctv.ejinr";// com.公司名.项目名
	private static String beanName;
	private static String tableName;
	private static List<String> fileds = new ArrayList<String>();
	private static List<String> types = new ArrayList<String>();
	private static List<String> texts = new ArrayList<String>();

	public static void main(String[] args) {
		try {
			File f = new File(".");
			String path1 = f.getAbsolutePath();
			baseDir=path1.substring(0, path1.length() - 2);
			// 启动
			getBaseInfo4Xlsm();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 0,读取xlsm 形式
	public static void getBaseInfo4Xlsm() throws IOException, InterruptedException {
		XSSFWorkbook xssfWorkbook = new XSSFWorkbook(baseDir + "/" + xlsmName);
		// 读取目录
		XSSFSheet xssfSheetML = xssfWorkbook.getSheetAt(0);
		for (int i = 1; i <= xssfSheetML.getLastRowNum(); i++) {
			XSSFRow rowML = xssfSheetML.getRow(i);
			if (rowML == null) {
				continue;
			}
			String tbName = getXlssVal(rowML.getCell(2));
			String isOk = getXlssVal(rowML.getCell(4));

			if (isNotEmpty(tbName) && isNotEmpty(isOk)) {
				if ("yes".equals(isOk)) {
					XSSFSheet xssfSheet = xssfWorkbook.getSheet(tbName);
					//
					if (null != xssfSheet) {
						// 装数
						tableName = xssfSheet.getSheetName();
						String[] ss = tableName.split("_");
						moduleName = ss[0];
						String str = ss[1];
						beanName = str.substring(0, 1).toUpperCase() + str.substring(1, str.length());
						fileds.clear();
						types.clear();
						texts.clear();
						//
						for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
							XSSFRow xssfRow = xssfSheet.getRow(rowNum);
							String text = getXlssVal(xssfRow.getCell(1));
							String filed = getXlssVal(xssfRow.getCell(2));
							String type = getXlssVal(xssfRow.getCell(3));
							fileds.add(filed);
							types.add(getFiledType(type));
							texts.add(text);
						}
						// 开始
						createJavaBean();

						createDao();

						createDaoXml();

						createService();

						createServiceImpl();

						createWebController();

						toFormDiv();
						// 结束
					}
					// 改变已经生成过的代码
					rowML.getCell(4).setCellValue("not");
				}
			}
		}
		//写出excel
		OutputStream out=new FileOutputStream(baseDir + "/"+xlsmName.substring(0,xlsmName.indexOf("."))+"New.xlsm");
		xssfWorkbook.write(out);
		xssfWorkbook.close();
		out.flush();
		out.close();
		//
		
	}

	// 2,根据读取的信息，创建实体类,{entity}.java
	public static void createJavaBean() {
		// 创建包
		String javaFilePath = baseDir + "/" + packagePath + "/" + moduleName + "/bean";
		createPackage(javaFilePath);
		// 代码
		StringBuffer sb = new StringBuffer();
		sb.append("package " + packageName + "." + moduleName + ".bean;\n\n");// 包
		sb.append("import java.io.Serializable;\n");
		sb.append("import java.util.*;\n\n");

		sb.append("public class " + beanName + "  implements Serializable{\n");// 类

		sb.append("    private static final long serialVersionUID = 1L;\n");
		for (int i = 0; i < fileds.size(); i++) {
			sb.append("    private " + types.get(i) + " " + fileds.get(i) + ";\n");
		}
		sb.append("}\n");
		writeS(new String(sb), "utf-8", javaFilePath + "/" + beanName + ".java");
	}

	// 3-1,根据读取的信息，创建实体Dao,{entity}Dao.java\{entity}Dao.xml
	public static void createDao() {
		// 创建包
		String javaFilePath = baseDir + "/" + packagePath + "/" + moduleName + "/dao";
		createPackage(javaFilePath);
		// 代码
		StringBuffer sb = new StringBuffer();
		sb.append("package " + packageName + "." + moduleName + ".dao;\n\n");// 包
		sb.append("import java.util.*;\n");
		sb.append("import org.springframework.stereotype.Repository;\n");
		sb.append("import " + packageName + "." + moduleName + ".bean." + beanName + ";\n\n");// 导包

		sb.append("@Repository\n");
		sb.append("public interface " + beanName + "Dao{\n\n");// 类

		sb.append("    int addBean(" + beanName + " bean);\n\n");
		sb.append("    int updateBean(" + beanName + " bean);\n\n");
		sb.append("    int deleteBean(String id);\n\n");
		sb.append("    " + beanName + " queryBean(String id);\n\n");
		sb.append("    List<" + beanName + "> queryAll(Map<String, Object> map);\n\n");
		sb.append("    long queryCount(Map<String, Object> map);\n\n");

		sb.append("}\n");
		writeS(new String(sb), "utf-8", javaFilePath + "/" + beanName + "Dao.java");
	}

	// 3-2,根据读取的信息，创建实体Dao,{entity}Dao.java\{entity}Dao.xml
	public static void createDaoXml() {
		// 创建包
		String javaFilePath = baseDir + "/" + packagePath + "/" + moduleName + "/dao";
		createPackage(javaFilePath);
		// 代码
		StringBuffer sb = new StringBuffer();
		// head
		sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
		sb.append(
				"<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\"\n\"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">\n");
		sb.append("<mapper namespace=\"" + packageName + "." + moduleName + ".dao." + beanName + "Dao\">\n\n");

		// 表
		sb.append("    <!-- 表 -->\n");
		sb.append("    <sql id=\"Table_Name\">\n");
		sb.append("        " + tableName + "\n");
		sb.append("    </sql>\n\n");

		// 字段
		sb.append("    <!-- 字段 -->\n");
		sb.append("    <sql id=\"Base_Column_List\">\n");
		String column = "        ";
		for (int i = 0; i < fileds.size(); i++) {
			if (i != 0 && i % 5 == 0) {
				column += "\n        ";
			}
			String f = fileds.get(i);
			if (isNotEmpty(f)) {
				column += f + ",";
			}
		}
		column = column.substring(0, column.length() - 1);
		sb.append(column + "\n");
		sb.append("    </sql>\n\n");
		//

		// add
		sb.append("    <!-- 新增 -->\n");
		sb.append("    <insert id=\"addBean\" parameterType=\"" + beanName + "\">\n");
		sb.append("        INSERT INTO\n");
		sb.append("        <include refid=\"Table_Name\" />\n");
		sb.append("        (\n");
		sb.append("        <include refid=\"Base_Column_List\" />\n");
		sb.append("        ) VALUES\n");
		sb.append("        (\n");
		String columnkh = "        ";
		for (int i = 0; i < fileds.size(); i++) {
			if (i != 0 && i % 5 == 0) {
				columnkh += "\n        ";
			}
			String f = fileds.get(i);
			if (isNotEmpty(f)) {
				columnkh += "#{" + f + "},";
			}
		}
		columnkh = columnkh.substring(0, columnkh.length() - 1);
		sb.append(columnkh + "\n");
		sb.append("        )\n");
		sb.append("    </insert>\n\n");
		//

		// upt
		sb.append("    <!-- 修改 -->\n");
		sb.append("    <update id=\"updateBean\" parameterType=\"" + beanName + "\">\n");
		sb.append("        UPDATE\n");
		sb.append("        <include refid=\"Table_Name\" />\n");
		sb.append("        <set>\n");
		sb.append("            <include refid=\"updateSQL\"/>\n");
		sb.append("        </set>\n");
		sb.append("        WHERE id = #{id}\n");
		sb.append("    </update>\n\n");

		// del
		sb.append("    <!-- 删除 -->\n");
		sb.append("    <delete id=\"deleteBean\" parameterType=\"java.lang.String\">\n");
		sb.append("        DELETE FROM\n");
		sb.append("        <include refid=\"Table_Name\" />\n");
		sb.append("        WHERE id = #{id}\n");
		sb.append("    </delete>\n\n");

		// queryBean
		sb.append("    <!-- 查询单个 -->\n");
		sb.append("    <select id=\"queryBean\" parameterType=\"java.lang.String\" resultType=\"" + beanName + "\">\n");
		sb.append("        SELECT <include refid=\"Base_Column_List\" /> FROM \n");
		sb.append("        <include refid=\"Table_Name\" />\n");
		sb.append("        WHERE id = #{id}\n");
		sb.append("    </select>\n\n");

		// queryAll
		sb.append("    <!-- 查询所有 -->\n");
		sb.append("    <select id=\"queryAll\" parameterType=\"java.util.Map\" resultType=\"" + beanName + "\">\n");
		sb.append("        SELECT <include refid=\"Base_Column_List\" /> FROM \n");
		sb.append("        <include refid=\"Table_Name\" />\n");
		sb.append("        <include refid=\"condition\" />\n");
		sb.append("        <include refid=\"splitPages\" />\n");
		sb.append("    </select>\n\n");

		// queryCount
		sb.append("    <!-- 查询总数 -->\n");
		sb.append("    <select id=\"queryCount\" parameterType=\"java.util.Map\" resultType=\"java.lang.Long\">\n");
		sb.append("        SELECT COUNT(*) FROM \n");
		sb.append("        <include refid=\"Table_Name\" />\n");
		sb.append("        <include refid=\"condition\" />\n");
		sb.append("    </select>\n\n");

		// uptsql
		sb.append("    <sql id=\"updateSQL\">\n");
		String uptsql = "";
		for (int i = 0; i < fileds.size(); i++) {
			String f = fileds.get(i);
			if (isNotEmpty(f)) {
				uptsql += "        <if test=\"" + f + " != null\">" + f + " = #{" + f + "},</if>\n";
			}
		}
		sb.append(uptsql + "\n");
		sb.append("    </sql>\n\n");

		// con
		sb.append("    <sql id=\"condition\">\n");
		sb.append("        <where>\n");
		String consql = "";
		for (int i = 0; i < fileds.size(); i++) {
			String f = fileds.get(i);
			if (isNotEmpty(f)) {
				consql += "            <if test=\"" + f + " != null\">AND " + f + " = #{" + f + "} </if>\n";
			}
		}
		sb.append(consql + "\n");
		sb.append("      </where>\n");
		sb.append("    </sql>\n\n");

		// split
		sb.append("    <sql id=\"splitPages\">\n");
		sb.append("        <if test=\"sortFiled != null\">\n");
		sb.append("            ORDER BY ${sortFiled}\n");
		sb.append("        </if>\n");
		sb.append("        <if test=\"sortFiled != null and direction != null \">\n");
		sb.append("            ${direction}\n");
		sb.append("        </if>\n");
		sb.append("        <if test=\"start!=null\">\n");
		sb.append("            LIMIT #{start}\n");
		sb.append("        </if>\n");
		sb.append("        <if test=\"start!=null and perpage!=null\">\n");
		sb.append("            ,#{perpage}\n");
		sb.append("        </if>\n");
		sb.append("    </sql>\n\n");
		sb.append("</mapper>\n");
		//
		writeS(new String(sb), "utf-8", javaFilePath + "/" + beanName + "Dao.xml");
	}

	// 4-1,根据读取的信息，创建实体service,{entity}Service.java\{entity}ServiceImpl.java
	public static void createService() {
		// 创建包
		String javaFilePath = baseDir + "/" + packagePath + "/" + moduleName + "/service";
		createPackage(javaFilePath);
		// 代码
		StringBuffer sb = new StringBuffer();
		sb.append("package " + packageName + "." + moduleName + ".service;\n\n");
		sb.append("import java.util.*;\n");
		sb.append("import " + packageName + "." + moduleName + ".bean." + beanName + ";\n\n");

		sb.append("public interface " + beanName + "Service{\n\n");

		sb.append("    int addBean(" + beanName + " bean);\n\n");
		sb.append("    int updateBean(" + beanName + " bean);\n\n");
		sb.append("    int deleteBean(String id);\n\n");
		sb.append("    " + beanName + " queryBean(String id);\n\n");
		sb.append("    List<" + beanName + "> queryAll(Map<String, Object> map);\n\n");
		sb.append("    long queryCount(Map<String, Object> map);\n\n");

		sb.append("}\n");
		writeS(new String(sb), "utf-8", javaFilePath + "/" + beanName + "Service.java");
	}

	// 4-2,根据读取的信息，创建实体service,{entity}Service.java\{entity}ServiceImpl.java
	public static void createServiceImpl() {
		// 创建包
		String javaFilePath = baseDir + "/" + packagePath + "/" + moduleName + "/service/impl";
		createPackage(javaFilePath);
		// 代码
		StringBuffer sb = new StringBuffer();
		sb.append("package " + packageName + "." + moduleName + ".service.impl;\n\n");
		sb.append("import java.util.*;\n\n");

		sb.append("import org.springframework.beans.factory.annotation.Autowired;\n");
		sb.append("import org.springframework.stereotype.Service;\n\n");

		sb.append("import " + packageName + "." + moduleName + ".bean." + beanName + ";\n");
		sb.append("import " + packageName + "." + moduleName + ".dao." + beanName + "Dao;\n");
		sb.append("import " + packageName + "." + moduleName + ".service." + beanName + "Service;\n\n");

		sb.append("@Service\n");
		sb.append("public class " + beanName + "ServiceImpl  implements " + beanName + "Service {\n\n");

		String dao = beanName.toLowerCase() + "Dao";
		sb.append("    @Autowired\n");
		sb.append("    private " + beanName + "Dao " + dao + ";\n\n");

		sb.append("    public int addBean(" + beanName + " bean){\n");
		sb.append("        return " + dao + ".addBean(bean);\n");
		sb.append("    }\n\n");

		sb.append("    public int updateBean(" + beanName + " bean){\n");
		sb.append("        return " + dao + ".updateBean(bean);\n");
		sb.append("    }\n\n");

		sb.append("    public int deleteBean(String id){\n");
		sb.append("        return " + dao + ".deleteBean(id);\n");
		sb.append("    }\n\n");

		sb.append("    public " + beanName + " queryBean(String id){\n");
		sb.append("        return " + dao + ".queryBean(id);\n");
		sb.append("    }\n\n");

		sb.append("    public List<" + beanName + "> queryAll(Map<String, Object> map){\n");
		sb.append("        return " + dao + ".queryAll(map);\n");
		sb.append("    }\n\n");

		sb.append("    public long queryCount(Map<String, Object> map){\n");
		sb.append("        return " + dao + ".queryCount(map);\n");
		sb.append("    }\n\n");

		sb.append("}\n");
		writeS(new String(sb), "utf-8", javaFilePath +"/"+ beanName + "ServiceImpl.java");
	}

	// 5,根据读取的信息，创建实体controller
	public static void createWebController() {
		// 创建包
		String javaFilePath = baseDir + "/" + packagePath + "/" + moduleName + "/web/controller";
		createPackage(javaFilePath);
		// 代码
		StringBuffer sb = new StringBuffer();
		sb.append("package "+ packageName + "." + moduleName + ".web.controller;\n\n");

		sb.append("import org.springframework.context.annotation.Scope;\n");
		sb.append("import org.springframework.web.bind.annotation.*;\n");
		sb.append("import org.springframework.stereotype.Controller;\n\n");

		sb.append("import com.aat.dxfy.base.web.controller.BaseController;\n\n");

		sb.append("@Controller\n@Scope(\"prototype\")\n@RequestMapping(\"master/" + beanName.toLowerCase() + "\")\n");
		sb.append("public class Master" + beanName + "Controller  extends BaseController{\n\n");

		sb.append("}\n");
		writeS(new String(sb), "utf-8", javaFilePath+ "/Master" + beanName + "Controller.java");
	}

	// 6,创建html文件的DIV-Form表单文件
	public static void toFormDiv() {
		String str = "";
		int i = 0;
		for (String s : fileds) {
			if (null != s) {
				str = str + "<div class=\"form-group \">\n";
				str = str + "    <label for=\"" + s + "\" class=\"control-label col-lg-2\">" + texts.get(i)
						+ "</label>\n";
				str = str + "    <div class=\"col-lg-6\">\n";
				str = str + "        <input class=\" form-control\" id=\"" + s + "\" name=\"" + s + "\"  value=\"${m."
						+ s + "}\"  type=\"text\" required />\n";
				str = str + "    </div>\n</div>\n";
				i++;
			}
		}
		str += "\n\n\n";
		writeS(str, "utf-8", baseDir + "/div" + beanName + ".html");
	}

	// 100：取得XLSM 表格的值
	private static String getXlssVal(XSSFCell c) {
		if (c.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
			return String.valueOf(c.getBooleanCellValue());
		} else if (c.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
			return String.valueOf(c.getNumericCellValue());
		} else {
			return String.valueOf(c.getStringCellValue());
		}
	}

	// 101：根据字段类型，得到java的属性类型；
	private static String getFiledType(String str) {
		if (str.toLowerCase().contains("char")) {
			return "String";
		}
		if (str.toLowerCase().startsWith("int")) {
			return "Integer";
		}
		if (str.toLowerCase().contains("bigint")) {
			return "Long";
		}
		if (str.toLowerCase().contains("float") || str.toLowerCase().contains("double")
				|| str.toLowerCase().contains("num") || str.toLowerCase().contains("dec")) {
			return "Double";
		}
		if (str.toLowerCase().contains("date")) {
			return "Date";
		}
		return "String";
	}

	// 102：创建文件包
	private static void createPackage(String pathname) {
		File f = new File(pathname);
		if (!f.exists()) {
			f.mkdirs();
		}
	}

	// 103：判断不为空
	private static boolean isNotEmpty(String str) {
		if (null == str) {
			return false;
		}
		if ("".equals(str) || str.length() == 0) {
			return false;
		}
		return true;

	}

	// 104：写出文件
	private static void writeS(String str, String encoding, String file) {
		char[] cuf = str.toCharArray();// 将指定的字串序列化为byte[]
		try {
			OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file), encoding);
			out.write(cuf);
			out.flush();
			out.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	//

}
